package com.dina.saas.peccancy.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.dina.saas.peccancy.domain.Detail;
import com.dina.saas.peccancy.domain.Peccancy;
import com.dina.saas.peccancy.domain.ResponsePeccMsg;

public class NanJingParser implements Parser {

	public ResponsePeccMsg parsePeccs(ResponsePeccMsg peccMsg, String msg) {
		if (StringUtils.isBlank(msg)) {
			return peccMsg;
		}
		Document doc = Jsoup.parse(msg);
		List<Object> peccancyArray = getPeccsArrayByDoc(doc);
		peccMsg.getDetail().getPeccancyArray().addAll(peccancyArray);
		return peccMsg;
	}

	public ResponsePeccMsg parseAll(String msg) {
		ResponsePeccMsg peccMsg = new ResponsePeccMsg("listPecc", 1, "");
		if (msg == null) {
			peccMsg = new ResponsePeccMsg("listPecc", 0, "");
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			return peccMsg;
		}
		Document doc = Jsoup.parse(msg);
		List<Object> peccancyArray = getPeccsArrayByDoc(doc);
		if (peccancyArray.size() > 0) {
			Element pager = doc.getElementById("pager");
			pager.child(0).remove();
			Integer totalRecordNum = Integer.valueOf(pager.html().split("条")[0]
					.substring(1));
			peccMsg.setTotalRecordNum(totalRecordNum);
			peccMsg.setDetail(new Detail(peccancyArray));
			peccMsg.setResult(0);
		}
		return peccMsg;
	}

	private List<Object> getPeccsArrayByDoc(Document doc) {
		Elements trs = doc.select("table.tableList").select("tr");
		trs.remove(trs.size() - 1);
		trs.remove(0);
		List<Object> peccancyArray = new ArrayList<Object>();
		for (int i = 0; i < trs.size(); i++) {
			Element tr = trs.get(i);
			Elements tds = tr.children();
			Peccancy pecc = new Peccancy();
			for (int j = 0; j < tds.size(); j++) {
				Element td = tds.get(j);
				String value = td.html();
				switch (j) {
				case 0: {
					pecc.setId(value);
					break;
				}
				case 1: {
					// 监控编号暂时不要
				}
				case 2: {
					pecc.setTime(value);
					break;
				}
				case 3: {
					pecc.setPlace(value);
					break;
				}
				case 4: {
					String[] strAry = value.split("<font color=\"blue\">");
					pecc.setAction(strAry[0] + "["
							+ strAry[1].split("</font>")[0] + "]");
					break;

				}
				case 5: {
					value = td.child(0).html();
					pecc.setResult(value);
					break;
				}
				}
			}
			peccancyArray.add(pecc);
		}
		return peccancyArray;
	}
}
